Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
JavaScript - "forEach is not a function" inside fetch().then(); refuses to be converted to an array

so, I have made use of the fetch API to...

  1. get a JSON File off my local server
  2. insert the contents into a element, with appropriate Values, etc. (currently Non-Functional, but also not relevant)

The JSON File: roughly like this: [["hello.css", "world.css", "why.css"], "doesn't.css", "this.css", "work.css"]

The Conditions: if there is a big Group of Strings in an array, inside the array, then turn that into a <optgroup>.

Where it Fails: in the Initialization of the first forEach function.

What I have found out:

  • The Recieved Text is treated as an Object, obiously making it fail.
  • It also fails to convert it into an array. Either it is empty or fails differently. Look further below for my attempts.
  • It is already parsed, apperently, because with JSON.parse it throws an error, complaining about it.

The Code

fetch('./themes.json').then(theResponse => {
    let themesJSON = theResponse.text();
    console.log(themesJSON); /* All "console.log()" functions are for debugging purposes */
    themesJSON.forEach(elm => {
        let the = '';
        if (elm.length > 1) {
            let optgroup = document.createElement('optgroup');
            elm.forEach(elm => {
                let opt = document.createElement('option');
                opt.value = elm;
                opt.innerText = elm;
                optgroup.insertAdjacentElement('beforeend', opt);

                console.log(opt);
            })
            the.insertAdjacentElement("beforeend", optgroup)

            console.log(optgroup);
        } else {
            let opt = document.createElement('option');
            opt.value = elm;
            opt.innerText = elm;
            the.insertAdjacentElement('beforeend', opt);

            console.log(opt);
        }
        document.getElementById('themeSelection').insertAdjacentElement("beforeend", the);
        console.log(the);
    });
})

The Attempts

  • This Answer Here, returns an empty array, and is not an object anymore, i think
  • Another Answer under the same post, exact same result.
  • whatever this is, only tried the first option, as the other one, well, I didn't fully understand it, result? I don't recall anymore.
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are using:

let themesJSON = theResponse.text();

which returns a promise that resolves to a string.

What you need is JavaScript representation of your JSON file.

For that the correct syntax would be like this:

fetch('./themes.json')
.then(theResponse => theResponse.json())
.then(actualArray => {
    console.log(actualArray)
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda